package com.ash.tx.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ash.tx.bean.Book;
import com.ash.tx.bean.User;
import com.ash.tx.dao.BookDao;
import com.ash.tx.dao.UserDao;
import com.ash.tx.service.UserService;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private BookDao bookDao;
    @Autowired
    private UserDao userDao;

//    @Transactional
    @Override
    public void purchase(User user, Book book, Integer num) {
        Book bookBought = bookDao.queryBook(book.getId());

        bookBought.setStockNum(bookBought.getStockNum() - num);

        if (bookBought.getStockNum() <= 0) {
            throw new RuntimeException("book stock num is not enough");
        }

        // 减库存
        bookDao.updateBook(bookBought);

        // 减余额

        User userPurchase = userDao.queryUser(user.getId());

        userPurchase.setBalance(userPurchase.getBalance() - bookBought.getPrice() * num);

        if (userPurchase.getBalance() <= 0) {
            throw new RuntimeException("balance is not enough");
        }

        userDao.updateUser(userPurchase);
    }

}
